package cn.threewaters.qtyy.service.sys;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import cn.threewaters.qtyy.dit.one.dao.SysRoleDao;
import cn.threewaters.qtyy.dit.one.entity.SysRole;
import cn.threewaters.qtyy.dit.one.entity.SysRoleFunction;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

	@Autowired
	private SysRoleFunctionService sysRoleFunctionService;

	@Autowired
	private SysFunctionService sysFunctionService;

	@Override
	@Transactional
	public SysRole insertSysRole(SysRole sysRole) {
		this.insert(sysRole);
		String roleId = sysRole.getId();
		List<SysRoleFunction> sysRoleFunctionList = Lists.newArrayList();
		List<String> roleFunctionList = sysRole.getRoleFunction();
		for (String functionId : roleFunctionList) {
			if (functionId.equals("0")) {
				continue;
			}
			SysRoleFunction sysRoleFunction = new SysRoleFunction();
			sysRoleFunction.setFunctionId(functionId);
			sysRoleFunction.setRoleId(roleId);
			sysRoleFunctionList.add(sysRoleFunction);
		}
		if (sysRoleFunctionList.size() > 0) {
			sysRoleFunctionService.insertBatch(sysRoleFunctionList);
		}
		return sysRole;
	}

	@Override
	@Transactional
	public SysRole updateSysRole(SysRole sysRole) {
		this.updateById(sysRole);

		String roleId = sysRole.getId();
		List<Map<String, String>> oldSysRoleFunctionList = sysFunctionService.getRoleZtreeData(roleId);
		List<String> oldSysFunctionIdList = Lists.newArrayList();
		for (Map<String, String> sysRoleFunction : oldSysRoleFunctionList) {
			oldSysFunctionIdList.add(sysRoleFunction.get("id").toString());
		}
		List<String> newSysFunctionIdList = sysRole.getRoleFunction();
		newSysFunctionIdList.remove("0");
		// 需要新增的
		List<String> waitAddList = Lists.newArrayList();
		waitAddList.addAll(newSysFunctionIdList);
		waitAddList.removeAll(oldSysFunctionIdList);
		List<SysRoleFunction> sysRoleFunctionList = Lists.newArrayList();
		for (String functionId : waitAddList) {
			SysRoleFunction sysRoleFunction = new SysRoleFunction();
			sysRoleFunction.setFunctionId(functionId);
			sysRoleFunction.setRoleId(roleId);
			sysRoleFunctionList.add(sysRoleFunction);
		}
		if (sysRoleFunctionList.size() > 0) {
			sysRoleFunctionService.insertBatch(sysRoleFunctionList);
		}
		// 需要删除的
		List<String> waitDeleteList = Lists.newArrayList();
		waitDeleteList.addAll(oldSysFunctionIdList);
		waitDeleteList.removeAll(newSysFunctionIdList);
		if (waitDeleteList.size() > 0) {
			sysRoleFunctionService.delete(
					new EntityWrapper<SysRoleFunction>().eq("role_id", roleId).in("function_id", waitDeleteList));
		}

		return sysRole;
	}
}
